<template>
  <common-layout title="仓库列表">
    <template #header-buttons>
      <el-button type="primary" @click="handleCreate">创建仓库</el-button>
    </template>

    <template #search-form>
      <el-form :inline="true" :model="searchForm" class="mb-4">
        <el-form-item label="仓库编码">
          <el-input v-model="searchForm.warehouseCode" placeholder="请输入仓库编码" />        </el-form-item>
        <el-form-item label="仓库名称">
          <el-input v-model="searchForm.warehouseName" placeholder="请输入仓库名称" />        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </template>

    <template #data-content>

      <el-table :data="warehouseList" style="width: 100%">
        <el-table-column prop="warehouseCode" label="仓库编码" width="180" />
        <el-table-column prop="warehouseName" label="仓库名称" width="180" />
        <el-table-column prop="description" label="描述" width="200" />
        <el-table-column prop="address" label="地址" width="250" />
        <el-table-column prop="status" label="状态" width="100" :formatter="formatStatus" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleView(row)">查看</el-button>
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 查看/编辑/创建对话框 -->
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
      >
        <el-form :model="warehouseForm" ref="warehouseFormRef" label-width="120px">
          <el-form-item label="仓库编码" :required="true">
            <el-input v-model="warehouseForm.warehouseCode" :disabled="dialogType === 'view' || dialogType === 'edit'" />
          </el-form-item>
          <el-form-item label="仓库名称" :required="true">
            <el-input v-model="warehouseForm.warehouseName" :disabled="dialogType === 'view'" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="warehouseForm.description" type="textarea" :disabled="dialogType === 'view'" />
          </el-form-item>
          <el-form-item label="地址">
            <el-input v-model="warehouseForm.address" :disabled="dialogType === 'view'" />
          </el-form-item>
          <el-form-item label="状态" :required="true">
            <el-select v-model="warehouseForm.status" :disabled="dialogType === 'view'">
              <el-option label="启用" value="1" />
              <el-option label="禁用" value="0" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button v-if="dialogType !== 'view'" type="primary" @click="handleSubmit">确定</el-button>
          </div>
        </template>
      </el-dialog>
    </template>
  </common-layout>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 搜索表单数据
const searchForm = reactive({
  warehouseCode: '',
  warehouseName: '',
  status: ''
})

// 仓库列表数据
const warehouseList = ref([])

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 对话框数据
const dialogVisible = ref(false)
const dialogType = ref('') // 'create', 'edit', 'view'
const dialogTitle = ref('')
const warehouseForm = reactive({})
const warehouseFormRef = ref(null)

// 格式化状态
const formatStatus = (row) => {
  return row.status === 1 ? '启用' : '禁用'
}

// 加载仓库列表数据
const loadWarehouseList = async () => {
  try {
    const response = await axios.get('/api/Warehouses/paged', {
      params: {
        page: pagination.currentPage,
        pageSize: pagination.pageSize,
        warehouseCode: searchForm.warehouseCode,
        warehouseName: searchForm.warehouseName,
        status: searchForm.status
      }
    })
    warehouseList.value = response.data.items
    pagination.total = response.data.total
  } catch (error) {
    ElMessage.error('获取仓库列表失败: ' + error.message)
    console.error('Failed to load warehouse list:', error)
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  loadWarehouseList()
}

// 重置
const handleReset = () => {
  searchForm.warehouseCode = ''
  searchForm.warehouseName = ''
  searchForm.status = ''
  pagination.currentPage = 1
  loadWarehouseList()
}

// 分页大小变更
const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadWarehouseList()
}

// 当前页变更
const handleCurrentChange = (current) => {
  pagination.currentPage = current
  loadWarehouseList()
}

// 打开创建对话框
const handleCreate = () => {
  dialogType.value = 'create'
  dialogTitle.value = '创建仓库'
  warehouseForm.id = 0
  warehouseForm.warehouseCode = ''
  warehouseForm.warehouseName = ''
  warehouseForm.description = ''
  warehouseForm.address = ''
  warehouseForm.status = 1
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  dialogTitle.value = '编辑仓库'
  try {
    const response = await axios.get(`/api/Warehouses/${row.id}`)
    Object.assign(warehouseForm, response.data)
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取仓库详情失败: ' + error.message)
  }
}

// 打开查看对话框
const handleView = async (row) => {
  dialogType.value = 'view'
  dialogTitle.value = '查看仓库'
  try {
    const response = await axios.get(`/api/Warehouses/${row.id}`)
    Object.assign(warehouseForm, response.data)
    dialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取仓库详情失败: ' + error.message)
  }
}

// 删除仓库
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这个仓库吗？', '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await axios.delete(`/api/Warehouses/${row.id}`)
    ElMessage.success('删除成功')
    loadWarehouseList()
  } catch (error) {
    if (error.name !== 'Error') {
      ElMessage.error('删除失败: ' + error.message)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await warehouseFormRef.value.validate()
    if (dialogType.value === 'create') {
      await axios.post('/api/Warehouses', warehouseForm)
      ElMessage.success('创建成功')
    } else if (dialogType.value === 'edit') {
      await axios.put(`/api/Warehouses/${warehouseForm.id}`, warehouseForm)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    loadWarehouseList()
  } catch (error) {
    ElMessage.error('提交失败: ' + error.message)
  }
}

// 初始化加载数据
onMounted(() => {
  loadWarehouseList()
})
</script>

<style scoped>
.pagination-container {
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>